# 用一个简单的界面完成NLP任务

import os
import io
# pprint包可以更好的展示json格式的内容
import pprint
# 导入一些必要的包
import requests, json
from IPython.display import Image, display, HTML
from PIL import Image
import base64
# 导入所需的库
import gradio as gr

hf_api_key = "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"



#总结函数
def get_completion(inputs, parameters=None,ENDPOINT_URL="https://djxvynvgjd0317xo.us-east-1.aws.endpoints.huggingface.cloud"):
    headers = {
      "Authorization": f"Bearer {hf_api_key}",
      "Content-Type": "application/json"
    }
    data = { "inputs": inputs }
    if parameters is not None:
        data.update({"parameters": parameters})
    response = requests.request("POST",
                                ENDPOINT_URL, headers=headers,
                                data=json.dumps(data)
                               )
    return json.loads(response.content.decode("utf-8"))

# 测试
# text_en = '''The tower is 324 metres (1,063 ft) tall, about the same height
#         as an 81-storey building, and the tallest structure in Paris.
#         Its base is square, measuring 125 metres (410 ft) on each side.
#         During its construction, the Eiffel Tower surpassed the Washington
#         Monument to become the tallest man-made structure in the world,
#         a title it held for 41 years until the Chrysler Building
#         in New York City was finished in 1930. It was the first structure
#         to reach a height of 300 metres. Due to the addition of a broadcasting
#         aerial at the top of the tower in 1957, it is now taller than the
#         Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the
#         Eiffel Tower is the second tallest free-standing structure in France
#         after the Millau Viaduct.'''
# pprint.pprint(get_completion(text_en))


# 定义生成文本摘要的函数
def summarize(input):
    output = get_completion(input)  # 使用之前定义的文本摘要生成函数
    return output[0]['summary_text']

# 关闭所有之前的Gradio界面（如果有的话）
gr.close_all()

# 创建Gradio界面
demo = gr.Interface(
    fn=summarize,  # 指定要用于处理输入的函数
    inputs=[gr.Textbox(label="Text to summarize", lines=6)],  # 输入部分的设置
    outputs=[gr.Textbox(label="Result", lines=3)],  # 输出部分的设置
    title="Text summarization with distilbart-cnn",  # 界面标题
    description="Summarize any text using the `shleifer/distilbart-cnn-12-6` model under the hood!"  # 界面描述
)

# 启动共享模式的界面，允许其他用户访问
demo.launch(share=True)